from django.contrib import admin
from django.contrib.auth.models import User
from django.urls import path
from django.shortcuts import render
from django.utils.translation import gettext_lazy as _
from django.contrib.admin.views.decorators import staff_member_required
from django.utils.decorators import method_decorator

from .models import Music, UserProfile, Rating, Comment, PlayHistory
from .admin_context import admin_stats

admin.site.site_title = "音乐推荐系统后台管理系统"
admin.site.site_header = "音乐推荐系统-后台管理系统"
admin.site.index_title = "音乐推荐系统"


# 内联管理
class LikesInline(admin.TabularInline):
    model = UserProfile.likes.through
    extra = 0
    verbose_name = '喜欢的歌曲'
    verbose_name_plural = verbose_name


class DislikesInline(admin.TabularInline):
    model = UserProfile.dislikes.through
    extra = 0
    verbose_name = '不喜欢的歌曲'
    verbose_name_plural = verbose_name


# 音乐评分内联管理
class RatingInline(admin.TabularInline):
    model = Rating
    extra = 0
    readonly_fields = ('user', 'score', 'created_at', 'updated_at')
    can_delete = False
    verbose_name = '评分'
    verbose_name_plural = '评分列表'


# 音乐评论内联管理
class CommentInline(admin.TabularInline):
    model = Comment
    extra = 0
    readonly_fields = ('user', 'content', 'created_at')
    can_delete = True
    verbose_name = '评论'
    verbose_name_plural = '评论列表'


# 播放历史内联管理
class PlayHistoryInline(admin.TabularInline):
    model = PlayHistory
    extra = 0
    readonly_fields = ('user', 'played_at')
    can_delete = True
    verbose_name = '播放历史'
    verbose_name_plural = '播放历史列表'


@admin.register(Music)
class MusicAdmin(admin.ModelAdmin):
    list_display = ('song_name', 'artist_name', 'genre_ids', 'average_rating')
    list_filter = ('genre_ids', 'language')
    search_fields = ('song_name', 'artist_name', 'genre_ids')
    inlines = [RatingInline, CommentInline, PlayHistoryInline]


@admin.register(UserProfile)
class UserProfileAdmin(admin.ModelAdmin):
    list_display = ('user', 'first_run')
    search_fields = ('user__username',)
    list_filter = ['genre_subscribe', 'language_subscribe']
    list_per_page = 12
    raw_id_fields = ['user']
    exclude = ('likes', 'dislikes')
    inlines = [LikesInline, DislikesInline]

    def user_id(self, obj: UserProfile):
        return obj.user.id


@admin.register(Rating)
class RatingAdmin(admin.ModelAdmin):
    list_display = ('user', 'music', 'score', 'created_at')
    list_filter = ('score', 'created_at')
    search_fields = ('user__username', 'music__song_name')


@admin.register(Comment)
class CommentAdmin(admin.ModelAdmin):
    list_display = ('user', 'music', 'content', 'created_at')
    list_filter = ('created_at',)
    search_fields = ('user__username', 'music__song_name', 'content')


@admin.register(PlayHistory)
class PlayHistoryAdmin(admin.ModelAdmin):
    list_display = ('user', 'music', 'played_at')
    list_filter = ('played_at',)
    search_fields = ('user__username', 'music__song_name')
    date_hierarchy = 'played_at'
    readonly_fields = ('user', 'music', 'played_at')


# 自定义管理后台
class MusicAdminSite(admin.AdminSite):
    index_template = 'admin/index.html'
    
    def each_context(self, request):
        context = super().each_context(request)
        # 添加额外的JavaScript
        context.update({
            'has_chartjs': True,
        })
        return context
        
    def get_urls(self):
        urls = super().get_urls()
        custom_urls = [
            path('dashboard/', self.admin_view(self.dashboard_view), name='dashboard'),
        ]
        return custom_urls + urls
    
    def dashboard_view(self, request):
        stats = admin_stats(request)
        print("Dashboard stats:", stats)  # 调试信息
        
        # 确保图表数据是有效的JSON字符串
        for key in ['month_labels', 'rating_counts', 'comment_counts', 'genre_labels', 'genre_counts', 'language_labels', 'language_counts']:
            if key in stats and stats[key] is None:
                stats[key] = "[]"
                
        # 确保有基础统计数据
        if 'music_count' not in stats or stats['music_count'] is None:
            stats['music_count'] = 0
        if 'user_count' not in stats or stats['user_count'] is None:
            stats['user_count'] = 0 
        if 'rating_count' not in stats or stats['rating_count'] is None:
            stats['rating_count'] = 0
        if 'comment_count' not in stats or stats['comment_count'] is None:
            stats['comment_count'] = 0
                
        # 为context提供默认值
        context = {
            **self.each_context(request),
            'stats': stats,
            'has_chartjs': True,  # 确保启用图表JS
            'music_count': stats.get('music_count', 0),  # 直接传递数据
            'user_count': stats.get('user_count', 0),
            'rating_count': stats.get('rating_count', 0),
            'comment_count': stats.get('comment_count', 0),
            'total_music': stats.get('music_count', 0),
            'total_users': stats.get('user_count', 0), 
            'total_ratings': stats.get('rating_count', 0),
            'total_comments': stats.get('comment_count', 0),
            'user_growth': stats.get('user_growth', []),
            'top_rated_music': stats.get('top_rated_music', []),
            'recent_music': stats.get('recent_music', []),
            'recent_comments': stats.get('recent_comments', [])
        }
        
        print("Context keys:", context.keys())
        print("Stats music_count:", context['stats'].get('music_count'))
        print("Stats user_count:", context['stats'].get('user_count'))
        print("Stats rating_count:", context['stats'].get('rating_count'))
        
        return render(request, 'admin/index.html', context)


# 修改默认的admin站点
admin.site.__class__ = MusicAdminSite
admin.site.site_header = '音乐推荐系统管理后台'
admin.site.site_title = '音乐推荐系统'
admin.site.index_title = '管理面板'
